import { supabase } from "../utils/supabase";

export default {
  addCart({ dispatch, state }, body) {
    let { info, num } = body;
    const list = [...state.cartList];
    const cartChecked = [...state.cartChecked];
    const idx = list.findIndex((it) => it.id == info.id);
    const idx2 = cartChecked.indexOf(info.id);
    // if (num === undefined) {
    //   num = (list[idx]?.num || 0) + 1;
    // }
    if (idx2 > -1) {
      cartChecked.splice(idx2, 1);
    }
    if (idx > -1) {
      list.splice(idx, 1);
    }

    if (num) {
      cartChecked.push(info.id);
      list.unshift({
        ...info,
        num,
      });
    }
    return dispatch("setStore", {
      cartList: list,
      cartChecked,
    });
  },
  async getTreeInfo({ dispatch, state }) {
    const {
      data: { user, goods },
    } = await uni.$api.get("/bot/auth/tree-info");
    const userMeta = state.userInfo.user_metadata;
    if (uni.$h.inMp) {
      if (
        userMeta.status !== user.status ||
        userMeta.got_tree != user.got_tree
      ) {
        await dispatch("postUserInfo", user);
      }
    }
    return goods;
  },
  async payOrder(_, body) {
    const { data } = await uni.$api.post(uni.$apiHub.postOrder, body);
    if (data.payment) {
      const info = await uni.$h.uniPay(data.payment);
      console.log(info);
    }
    return data;
  },
  async getShops({ dispatch }) {
    const { data } = await uni.$api.get(uni.$apiHub.shopList);
    return dispatch("setStore", {
      shops: data,
    });
  },
  async getMyLocation({ dispatch }) {
    const myLocation = await uni.$h.getLocation();
    return dispatch("setStore", {
      myLocation,
    });
  },

  async uploadFile({ state }, body) {
    const res = await supabase.auth.getSession();
    const data = await uni.$file.uploadFile(body.path, {
      ...body,
      header: {
        Authorization: "Bearer " + res.data?.session?.access_token,
      },
    });
    return data;
  },

  logout({ dispatch }) {
    return dispatch("setStore", {
      usrData: {},
      userInfo: {},
    });
  },
};
